package com.hqd.ch03.v50.boot.web.servlet;

import com.hqd.ch03.v50.beans.BeansException;
import com.hqd.ch03.v50.boot.autoconfigure.web.servlet.ServletRegistrationBean;
import com.hqd.ch03.v50.context.ApplicationContext;
import com.hqd.ch03.v50.context.ApplicationContextAware;
import com.hqd.ch03.v50.web.context.WebApplicationContext;
import com.hqd.ch03.v50.web.fliter.DelegatingFilterProxy;

import javax.servlet.ServletException;

public class DelegatingFilterProxyRegistrationBean extends AbstractFilterRegistrationBean<DelegatingFilterProxy>
        implements ApplicationContextAware {

    private final String targetBeanName;
    private ApplicationContext applicationContext;

    /**
     * Create a new {@link DelegatingFilterProxyRegistrationBean} instance to be
     * registered with the specified {@link ServletRegistrationBean}s.
     *
     * @param targetBeanName           name of the target filter bean to look up in the Spring
     *                                 application context (must not be {@code null}).
     * @param servletRegistrationBeans associate {@link ServletRegistrationBean}s
     */
    public DelegatingFilterProxyRegistrationBean(String targetBeanName,
                                                 ServletRegistrationBean<?>... servletRegistrationBeans) {
        super(servletRegistrationBeans);
        this.targetBeanName = targetBeanName;
        setName(targetBeanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    protected String getTargetBeanName() {
        return this.targetBeanName;
    }

    @Override
    public DelegatingFilterProxy getFilter() {
        return new DelegatingFilterProxy(this.targetBeanName, getWebApplicationContext()) {

            @Override
            protected void initFilterBean() throws ServletException {
                // Don't initialize filter bean on init()
            }

        };
    }

    private WebApplicationContext getWebApplicationContext() {
        return (WebApplicationContext) this.applicationContext;
    }

}
